package com.nuanshui.heatedloan.baseservice.service;

import com.nuanshui.framework.lang.DateUtil;
import com.nuanshui.heatedloan.baseservice.dal.mapper.DealNumMapper;
import com.nuanshui.heatedloan.baseservice.dal.mapper.IncrKeyMapper;
import com.nuanshui.heatedloan.baseservice.facade.OrderNumGenerate;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.constant.TransactionManagerType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;

@Service(ServiceConstant.ORDERNUMGENERATE)
public class OrderNumGenerateImpl implements OrderNumGenerate  {

	@Autowired
	private IncrKeyMapper incrKeyMapper;
	
	@Autowired
	private DealNumMapper dealNumMapper;

	
	@Value("${dealNum.prefix}")
	private String frefix = "";
	 
	
	public synchronized Long getMaxNum(String key) {
		Long num =  incrKeyMapper.findMaxNumBykey(key);
		if(num == null) {//表示今天还没有订单
			incrKeyMapper.insertKeyNum(key);
			return 1l;
		}else {
			incrKeyMapper.incrNumBykey(key);
			return num+1;
		}
	}
	
		
	private    String LongToString(Long num,int bitNum) {
		
		char[] chs = new char[bitNum];
		for(int i =0;i<chs.length;i++) {
			chs[i] = '0';
		}
		DecimalFormat df = new DecimalFormat(new String(chs));
		return df.format(num);	
	}

	@Override
	@Transactional(isolation=Isolation.SERIALIZABLE,propagation=Propagation.REQUIRES_NEW,value=TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
	public String getOrderNum(String key,int length) {

		StringBuilder sb = new StringBuilder(key);
		Long num = getMaxNum(key);
		sb.append(LongToString(num, length));
		return sb.toString();
	}


	@Override
	public String getDealNum(String bizType) {
		String day = DateUtil.getToday("yyMMdd");
		StringBuilder sb = new StringBuilder(day);
		sb.append("1");
		sb.append(bizType);	
		Long num = getMaxNum(day+bizType);
		sb.append(LongToString(num, 4));
		return sb.toString()+frefix;
	}


	//@Transactional(isolation=Isolation.SERIALIZABLE,propagation=Propagation.REQUIRES_NEW,value=TransactionManagerType.TRANSACTIONMANAGER)
		private synchronized Long getMaxOrderNum(String day) {
			Long num =  dealNumMapper.findMaxOrderNumByDay(day);
			if(num == null) {//表示今天还没有订单
				dealNumMapper.insertOrderNum(day);
				return 1l;
			}else {
				dealNumMapper.incrNumByDay(day);
				return num+1;
			}
		}


		@Override
		public String getOrderNum(String businessType) {
			String day = DateUtil.getToday("yyMMdd");
			StringBuilder sb = new StringBuilder(day);
			sb.append(businessType);
			Long num = getMaxOrderNum(day);
			sb.append(LongToString(num, 4));
			return sb.toString()+frefix;
		}

    
}
